module.exports = {
	// 经纬度转化。纬度在前，经度在后
	stringFromGeoPoint(point) {
		const {coordinates, type = 'Point'} = point || {}
		if (coordinates && coordinates.length === 2) {
			return `${coordinates[1]},${coordinates[0]}`
		}
		return ''
	},
	/**
	 * 经纬度字符串转对象
	 * 并非真正的GeoPoint对象，仅是服务器返回的数据结构而已
	 */
	objFromGeoPoint(position = '') {
		const arr = position.split(',')
		if (arr.length === 2) {
			if (arr[0] >= -90 && arr[0] <= 90 && arr[1] >= -180 && arr[1] <= 180) {
				return {
					type: 'Point',
					coordinates: [parseFloat(arr[1]), parseFloat(arr[0])]
				}
			}
		}
		return undefined
	},
	/**
	 * 通过经纬度计算两点之间的距离
	 * place1。字符串或者上述对象
	 * place2。字符串或者上述对象
	 */
	calculateDistance(place1, place2) {
		
		const objFromPlace = (place) => {
			if (typeof(place) === 'string') {
				const arr = place.split(',')
				arr.map((item, i) => {
					arr[i] = parseFloat(item)
				})
				return arr
			} else {
				if (place && place.coordinates) {
					return [place.coordinates[1], place.coordinates[0]]
				}
			}
			return undefined
		}
		
		place1 = objFromPlace(place1)
		place2 = objFromPlace(place2)
		
		if (place1 && place2) {
			var lat1 = place1[0], lon1 = place1[1], lat2 = place2[0], lon2 = place2[1]
			const radians = Math.PI / 180
			const R = 6371 // 地球半径，单位为千米
				 
			const deltaLat = (lat2 - lat1) * radians
			const deltaLon = (lon2 - lon1) * radians
				 
			lat1 = lat1 * radians
			lat2 = lat2 * radians
				 
			const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
					  Math.cos(lat1) * Math.cos(lat2) *
			          Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2)
			const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
			const distance = R * c
			const res = Math.round(distance * 100) / 100
			return res
		}
		return undefined
	}
}